package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threablocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2021/7/15 15:15
 **/
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        // 校验参数 (检查登录)
        ApUser user = AppThreadLocalUtils.getUser();

        // 2. 查询行为实体数据
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的行为实体数据不存在");
        }
        // 3. 判断之前是否有阅读行为
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);

        if (readBehavior == null) {
            // 3.1 没有  保存阅读行为
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short)1); // 阅读次数

            readBehavior.setReadDuration(0);
            readBehavior.setPercentage((short)0);
            readBehavior.setLoadDuration((short)0);

            readBehavior.setCreatedTime(new Date()); //
            readBehavior.setUpdatedTime(new Date()); // 修改时间
            mongoTemplate.save(readBehavior);
        }else {
            // 3.2 有  修改阅读行为   次数+1   修改update时间
            readBehavior.setCount((short)(readBehavior.getCount() + 1));
            readBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(readBehavior);
        }
        return ResponseResult.okResult();
    }
}
